package com.bestv.engine.model;

import com.bestv.database.dao.DaoFactory;
import com.bestv.database.vo.ItemRelation;
import com.bestv.database.vo.Series;
import com.bestv.utils.cache.MemcacheHelper;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by Henry on 14-5-23.
 */
public abstract class RecommendationModel {
    protected boolean isRandomSort = false;
    protected boolean isRandomSelect = false;

    public List<RecommendationItem> recommend(long itemId, int typeId, int maxCount) {
        String cacheIdKey = getCacheIdKey(itemId);
        List<RecommendationItem> itemList = (ArrayList<RecommendationItem>) MemcacheHelper.getInstance().getObject(cacheIdKey);
        if (itemList != null) {
            if (isRandomSort) Collections.shuffle(itemList);
            return itemList;
        }

        itemList = getRecommendationItems(itemId, typeId, maxCount);
        MemcacheHelper.getInstance().addObject(cacheIdKey, itemList);
        return itemList;
    }

    protected List<RecommendationItem> getRecommendationItems(long itemId, int typeId, int maxCount) {
        List<RecommendationItem> itemList = new ArrayList<RecommendationItem>();
        List<Object> rs = getItemRelations(itemId, typeId, maxCount);
        for (Object object : rs) {
            RecommendationItem item = new RecommendationItem();
            ItemRelation relation = (ItemRelation) object;
            Series series = DaoFactory.getSeriesDao().findById(relation.getRightId());
            if (series == null) continue;

            item.setId(series.getId());
            item.setItemId(series.getMediaCode());
            item.setSeries(series.isSeries());
            item.setModelName(getClass().getSimpleName());
            item.setCharge(series.getPrice() != null && series.getPrice() > 0);
            item.setName(series.getName());
            item.setScore(relation.getSimilarity());
            item.setTypeId(series.getTypeId());
            item.setDomain(series.getDomain());
            itemList.add(item);
        }
        return itemList;
    }

    protected abstract List<Object> getItemRelations(long itemId, int typeId, int maxCount);

    public String getCacheIdKey(long id) {
        return String.format("%s-Id-%s", getClass().getSimpleName(), id);
    }

    public void setRandomSort(boolean isRandomSort) {
        this.isRandomSort = isRandomSort;
    }

    public void setRandomSelect(boolean isRandomSelect) {
        this.isRandomSelect = isRandomSelect;
    }
}
